package com.jackchong.base

import android.app.Application
import android.content.Context
import android.graphics.Rect
import android.util.Log
import androidx.camera.camera2.Camera2Config
import androidx.camera.core.CameraXConfig
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.blankj.utilcode.util.CrashUtils
import com.hjq.language.MultiLanguages
import com.jackchong.net.JBaseData
import com.jackchong.utils.*
import com.kongzue.dialog.util.DialogSettings
import com.luck.picture.lib.app.IApp
import com.luck.picture.lib.app.PictureAppMaster
import com.luck.picture.lib.engine.PictureSelectorEngine
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.FormatStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.tencent.mmkv.MMKV
import com.uber.autodispose.AutoDispose
import com.uber.autodispose.AutoDisposeConverter
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider


/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2018/12/14 9:20
 */
abstract class BaseApplication : Application(), IApp, CameraXConfig.Provider, BaseView, LifecycleOwner {


    companion object {
        @JvmField
        var RELEASE_MODE = false
        private var sInstance: BaseApplication? = null
        @JvmStatic
        val instance: Context?
            get() = sInstance

        init {
            //设置全局的Header构建器
            SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
                layout.setDisableContentWhenRefresh(true)
                layout.setEnableOverScrollBounce(true)
                val classicsHeader = ClassicsHeader(context)
                classicsHeader.setTextSizeTime(12f)
                classicsHeader.setTextSizeTitle(12f)
                classicsHeader.setDrawableSize(12f)
                classicsHeader
            }
            //设置全局的Footer构建器
            SmartRefreshLayout.setDefaultRefreshFooterCreator { context: Context, layout: RefreshLayout ->
                //指定为经典Footer，默认是 BallPulseFooter
                layout.setDisableContentWhenLoading(true)
                layout.setEnableOverScrollBounce(true)
                layout.setEnableAutoLoadMore(false)
                layout.setEnableOverScrollDrag(true)
                val classicsFooter = ClassicsFooter(context)
                classicsFooter.setTextSizeTitle(12f)
                classicsFooter.setDrawableSize(12f)
                classicsFooter
            }
        }

    }


    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(MultiLanguages.attach(base))
    }

    override fun onCreate() {
        super.onCreate()
        sInstance = this
        appLifecycle.currentState = Lifecycle.State.INITIALIZED
        appLifecycle.currentState = Lifecycle.State.CREATED
        appLifecycle.currentState = Lifecycle.State.STARTED
        appLifecycle.currentState = Lifecycle.State.RESUMED

        initDevice()

        MMKV.initialize(this);
        SPUtils.init(this)
        JToast.init(appContext)
        val strategy: FormatStrategy = PrettyFormatStrategy.newBuilder()
            .tag("jlog")
            .showThreadInfo(false)
            .methodOffset(0)
            .methodCount(0)
            .build()
        Logger.addLogAdapter(object : AndroidLogAdapter(strategy) {
            override fun isLoggable(priority: Int, tag: String?): Boolean {
                return super.isLoggable(priority, tag)
            }
        })
        MultiLanguages.init(this)
        PictureAppMaster.getInstance().app = this

        CrashUtils.init {
            JLog.e("jlog", Log.getStackTraceString(it.throwable))
        }

        DialogSettings.theme = (DialogSettings.THEME.LIGHT);
        DialogSettings.tipTheme = (DialogSettings.THEME.DARK);
        DialogSettings.style = (DialogSettings.STYLE.STYLE_MIUI)

        init()
    }

    private fun initDevice() {
        DeviceInfo.sUid = PackageInfoUtils.getUId(this)
        val screenSize = WindowUtils.getScreenSize(this)
        DeviceInfo.sScreenRect = Rect(0, 0, screenSize.widthPixels, screenSize.heightPixels)
        DeviceInfo.sAutoScaleX = DeviceInfo.sScreenRect.width() * 1.0f / DeviceInfo.UI_WIDTH
        DeviceInfo.sAutoScaleY = DeviceInfo.sScreenRect.height() * 1.0f / DeviceInfo.UI_HEIGHT
        DeviceInfo.sNavigationBarHeight = WindowUtils.getNavigationBarHeight(this)
        DeviceInfo.sStatusBarHeight = WindowUtils.getStatusBarHeight(this)
    }

    override fun onTerminate() {
        appLifecycle.currentState = Lifecycle.State.DESTROYED
        super.onTerminate()
    }


    override fun getPictureSelectorEngine(): PictureSelectorEngine {
        return PictureSelectorEngineImp()
    }


    override fun getCameraXConfig(): CameraXConfig {
        return Camera2Config.defaultConfig()
    }

    override fun getAppContext(): Context {
        return this
    }

    protected abstract fun init()


    private val appLifecycle = object : LifecycleRegistry(this) {  }

    override fun showLoading() {

    }

    override fun hideLoading() {
    }

    override fun lifecycle(): Lifecycle = appLifecycle

    override fun onFill(bean: JBaseData<*>) {
    }

    override fun onError(cause: Throwable) {

    }

    override fun <T> bindAutoDispose(): AutoDisposeConverter<T> = AutoDispose.autoDisposable(
            AndroidLifecycleScopeProvider
                    .from(appLifecycle, Lifecycle.Event.ON_DESTROY))

    override fun getLifecycle(): Lifecycle = appLifecycle


}